// packageC/selfCarry/selfCarry_info/selfCarry_info.js
var app = getApp();
var location = require("../../../mybehaviors/location/location");


Page({
  behaviors: [location],

  /**
   * 页面的初始数据
   */
  data: {
    show: false,
    point: {
      lat: "",
      lng: "",
    },
    kwd: "",
    city: "",
    info: [],
    detailinfo: {},
    openDateLw: false,
    provinceData: [],
    cityData: [],
    districtData: [],
    pickerValue: [0, 0, 0],
    selectAddressData: [],
    goodsId: "",
    optionsId: "",
    cart_ids: "",
    tag: "",
    total: "",
    // more
    page: 1, // 分页数，当前页数
    isLoadMore: true, // 判断是否要加载更多的标志
    total_page: 0, // 总页数
    iscloud: "",
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.iscloud) {
      this.setData({
        iscloud: options.iscloud,
      });
    }
    if (options.ind) {
      this.setData({
        ind: options.ind,
      });
    }
    this.setData({
      goodsId: options.goodsId,
      optionsId: options.optionsId,
      tag: options.tag,
      total: options.total,
      cart_ids: options.cart_ids,
      level_id: options.level_id,
      option_level_id: options.option_level_id,
      team_id:options.team_id
    });
    this._getLocation(() => {this.getList();});
    //加载地址数据初始化
    this._initAddressInfo();
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.isLoadMore) {
      this.getMoreData();
    } else {
      wx.showToast({
        title: "没有更多数据",
        icon: "none",
      });
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {},
  callPhone(e) {
    let detailinfo = e.currentTarget.dataset.phone;
    wx.makePhoneCall({
      phoneNumber: detailinfo,
    });
  },
  showDetail(e) {
    let detailinfo = e.currentTarget.dataset.v;
    this.setData({
      show: true,
      detailinfo,
    });
  },
  onClose() {
    this.setData({
      show: false,
      detailinfo: {},
    });
  },

  getList() {
    let that = this;
    let urlStr = app.getNetAddresss(
      "plugin.package-deliver.frontend.deliver.getList"
    );

    if(this.options.store_id||this.options.groupStoreID){
      urlStr = app.getNetAddresss("plugin.package-deliver.frontend.store.deliver.getList");
    }
    let point = app.qqMapTransBMap(
      parseFloat(that.data.point.lng),
      parseFloat(that.data.point.lat)
    );
    app._getNetWork({
      url: urlStr,
      data: {
        city_name: that.data.city,
        lat: point.lat,
        lng: point.lng,
        kwd: that.data.kwd,
        goods: that.options.goods || [],
        store_id: this.options.store_id ||this.options.groupStoreID|| ''
      },
      success: (resdata)=> {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            info: res.data.list.data,
            total_page: res.data.list.last_page,
            isLoadMore: true,
            page: res.data.list.current_page,
          });
          if (!that.data.total_page) {
            that.setData({
              total_page: 0,
            });
          }
        } else {
          wx.showToast({
            icon: "none",
            title: "获取自提点失败",
            duration: 1000,
          });
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  getMoreData() {
    let that = this;
    this.setData({
      isLoadMore: false,
    });
    if (this.data.page >= this.data.total_page) {
      return;
    } else {
      let pages = this.data.page;
      pages += 1;
      this.setData({
        page: pages,
      });
      let point = app.qqMapTransBMap(
        parseFloat(that.data.point.lng),
        parseFloat(that.data.point.lat)
      );
      let urlStr = app.getNetAddresss(
        "plugin.package-deliver.frontend.deliver.getList"
      );
      if(this.options.store_id||this.options.groupStoreID){
        urlStr = app.getNetAddresss("plugin.package-deliver.frontend.store.deliver.getList");
      }
      app._getNetWork({
        url: urlStr,
        data: {
          city_name: that.data.city,
          lat: point.lat,
          lng: point.lng,
          kwd: that.data.kwd,
          page: that.data.page,
          goods: that.options.goods || [],
          store_id: this.options.store_id ||this.options.groupStoreID|| ''
        },
        success: (resdata)=> {
          var res = resdata.data;
          if (res.result == 1) {
            var nextPageData = res.data.list.data;
            let info = [...that.data.info, ...nextPageData];
            that.setData({
              info,
              total_page: res.data.list.last_page,
            });
          }
        },
        fail: function (res) {
          console.log(res.msg);
        },
      });
    }
  },
  //打开地址选择器
  openDateLwtbtn: function () {
    this.setData({
      openDateLw: true,
    });
  },
  //地址选择器数据初始化
  _initAddressInfo: function () {
    var that = this;
    var _keyName = "provinceData";
    wx.getStorage({
      key: _keyName,
      success: function (res) {
        console.log("地址信息准备就绪");
        that._getProvinceData();
      },
      fail: function (res) {
        console.log("省fail");
        app._getNetWork({
          url: app.getNetAddresss("member.member-address.address"),
          success: function (res) {
            var response = res.data;
            var province = response.data.province;
            var city = response.data.city;
            var district = response.data.district;
            wx.setStorage({
              key: "provinceData",
              data: province,
            });
            wx.setStorage({
              key: "cityData",
              data: city,
            });
            wx.setStorage({
              key: "districtData",
              data: district,
            });
            that._initAddressInfo();
          },
          fail: function (res) {},
          state: true,
        });
      },
    });
  },
  // 读取省key
  _getProvinceData: function () {
    var that = this;
    var _keyName = "provinceData";
    wx.getStorage({
      key: _keyName,
      success: function (res) {
        console.log("省读取成功", res.data);
        that.setData({
          provinceData: res.data,
        });
        that.setData({
          "selectAddressData[0].name":
            res.data[that.data.pickerValue[0]].areaname,
          "selectAddressData[0].id": res.data[that.data.pickerValue[0]].id,
          "selectAddressData[0].index": that.data.pickerValue[0],
        });
        that._getCityData();
      },
    });
  },
  // 读取城市key，筛选城市data
  _getCityData: function () {
    var _data = this.data.selectAddressData[0];
    console.log("城市", "_data", _data);
    var that = this;
    var _keyName = "cityData";
    wx.getStorage({
      key: _keyName,
      success: function (res) {
        console.log("城市读取成功", res);

        var _json = [];
        for (var i = 0; i < res.data.length; i++) {
          if (res.data[i].parentid == _data.id) {
            _json.push(res.data[i]);
          }
        }
        console.log("城市数据筛选", _json);
        that.setData({
          cityData: _json,
        });
        that.setData({
          "selectAddressData[1].name": _json[that.data.pickerValue[1]].areaname,
          "selectAddressData[1].id": _json[that.data.pickerValue[1]].id,
          "selectAddressData[1].index": that.data.pickerValue[1],
        });
        that._getDistrictData();
      },
    });
  },
  // 读取地区key，筛选地区data
  _getDistrictData: function () {
    var _data = this.data.selectAddressData[1];
    console.log("地区", "_data", _data);
    console.log(_data);
    var that = this;
    var _keyName = "districtData";
    wx.getStorage({
      key: _keyName,
      success: function (res) {
        console.log("地区读取成功");
        var _json = [];
        for (var i = 0; i < res.data.length; i++) {
          if (res.data[i].parentid == _data.id) {
            _json.push(res.data[i]);
          }
        }
        console.log("地区数据筛选", _json);
        that.setData({
          districtData: _json,
        });
        console.log("districtData", _json);
        that.setData({
          "selectAddressData[2].name": _json[that.data.pickerValue[2]].areaname,
          "selectAddressData[2].id": _json[that.data.pickerValue[2]].id,
          "selectAddressData[2].index": that.data.pickerValue[2],
        });
        console.log("over", that.data.selectAddressData);
      },
    });
  },
  // 收货地址滚动事件
  bindChange: function (e) {
    var val = e.detail.value;
    if (this.data.pickerValue[0] != val[0]) {
      val[1] = 0;
      val[2] = 0;
    }
    if (this.data.pickerValue[1] != val[1]) {
      val[2] = 0;
    }
    this.setData({
      "pickerValue[0]": val[0],
      "pickerValue[1]": val[1],
      "pickerValue[2]": val[2],
    });
    this._initAddressInfo();
  },
  // 确定选择收货地址
  _okAddress: function () {
    let seleData = this.data.selectAddressData;
    this.setData({
      city: seleData[1].name,
    });
    this.getList();
    this._closeDateLw();
  },
  // 关闭选择收货地址
  _closeDateLw: function () {
    this.setData({
      openDateLw: false,
    });
  },
  tosearch(e) {
    let searchValue = e.detail.value;
    this.setData({
      kwd: searchValue,
    });
    this.getList();
  },
  gotoOrder() {
    let that = this;
    this.getNowPackageDeliver(this.data.detailinfo.id);
    let json = {
      deliver_name: that.data.detailinfo.deliver_name,
      deliver_mobile: that.data.detailinfo.deliver_mobile,
      full_address: that.data.detailinfo.full_address,
      id: that.data.detailinfo.id,
    };
    let changeSelfCarry = JSON.stringify(json);

    let url = "/packageD/buy/myOrder_v2/myOrder_v2?from=1&tag=" +
              that.data.tag +
              "&goodsId=" +
              that.data.goodsId +
              "&optionsId=" +
              that.data.optionsId +
              "&total=" +
              that.data.total +
              "&changeSelfCarry=" +
              changeSelfCarry;

    if(that.data.cart_ids) { url= url+ "&cart_ids=" + that.data.cart_ids }
    if(that.data.level_id) {
      url= url+ "&level_id=" + that.data.level_id + "&option_level_id=" + that.data.option_level_id;
    }

    if(that.data.team_id) {
      url= url+ "&team_id=" + that.data.team_id + "&option_level_id=" + that.data.option_level_id;
    }

    if(that.options.goodCollection) {
      url= url+ "&goodCollection=" + that.options.goodCollection;
    }

    if(this.data.ind) {
      url= url+ "&ind=" + this.data.ind;
    }
    if(this.options.store_id&&Number(this.options.store_id)>0) {
      url= url+ "&store_id=" + this.options.store_id;
    }
    if (this.options.groupStoreID) {
      // 门店id
      url = url + "&groupStoreID=" + this.options.groupStoreID;
    }
    if(this.options.plu) {
      url= url+ "&plu=" + this.options.plu;
    }

    if(this.options.exchangeData) {
      url = url + "&exchangeData=" + this.options.exchangeData;
    }

    if (app._isTextEmpty(this.data.iscloud)) {
      wx.redirectTo({
        url: url
      });
    } else {
      wx.redirectTo({
        url:
          "/packageE/others/cloudwarehouse/cloudOrder/cloudOrder?from=1&tag=" +
          that.data.tag +
          "&goodsId=" +
          that.data.goodsId +
          "&optionsId=" +
          that.data.optionsId +
          "&total=" +
          that.data.total +
          "&changeSelfCarry=" +
          changeSelfCarry +
          "&is_selected=8"
      });
    }
  },
  getNowPackageDeliver(_id){
    //更新自提点供应商的关联id
    let urlStr = app.getNetAddresss('plugin.package-deliver.frontend.decorate-deliver.getNowPackageDeliver');
    app._postNetWork({
      url: urlStr,
      data: {deliver_id: _id},
      success: (resdata) => {
        let res = resdata.data;
        if (res.result == 1) {
          let deliverIDStorage = wx.getStorageSync('deliverId')||null;
          if (deliverIDStorage) {
            //有记录才去更新sessionStorage（说明一开始进入的），不然影响到分享链接上参数
            wx.setStorageSync("deliverId", res.data.id);
          }
        } else {
          wx.showToast({
            title: res.msg,
            duration: 1000,
            icon: 'none'
          });
        }
      },
      fail: function (res) {
        console.log(res.msg);
      }
    });
  }
});
